package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constans.WmNewsMessageConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmNewsPageReqDto dto) {
        //1.参数检查
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //2.获取用户id
        WmUser wmUser = WmThreadLocalUtil.getWmUser();
        if(wmUser==null || wmUser.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"当前没有登录，需登录后操作");
        }
        LambdaQueryWrapper<WmNews> queryWrapper= Wrappers.lambdaQuery();
        //3.根据状态查询
        if(dto.getStatus()!=null){//不是全部
            queryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }

        //4.根据关键字查询
        if(StringUtils.isNotBlank(dto.getKeyword())){
            queryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }

        //5.根据频道id查询
        if(dto.getChannelId()!=null){
            queryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }

        //6.根据发布时间查询
        if(dto.getBeginPubdate()!=null && dto.getEndPubdate()!=null){
            queryWrapper.between(WmNews::getPublishTime,dto.getBeginPubdate(),dto.getEndPubdate());
        }

        //7.根据用户id查询
        queryWrapper.eq(WmNews::getUserId,wmUser.getId());

        IPage<WmNews> ipage=new Page<>(dto.getPage(),dto.getSize());

        ipage= page(ipage, queryWrapper);

        //7.返回数据
        ResponseResult result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) ipage.getTotal());
        result.setData(ipage.getRecords());
        return result;
    }

    /**
     * 文章发布-保存-修改-保存草稿三合一,主方法
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //1.参数校验
        if(dto==null || dto.getContent()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto.getType()==-1){//表示自动
            dto.setType(null);
        }
        //2.保存或者修改文章
        WmNews wmnews=new WmNews();
        BeanUtils.copyProperties(dto,wmnews);

        //封面图片
        List<String> images = dto.getImages();//[aaa.jpg,bbb.jpg]
        wmnews.setImages(StringUtils.join(images,","));//“aaa.jpg,bbb.jpg”
        wmnews.setCreatedTime(new Date());
        wmnews.setSubmitedTime(new Date());
        wmnews.setUserId(WmThreadLocalUtil.getWmUser().getId());

        saveOrUpdateWnews(wmnews);

        //3.判断是否是草稿
        if(dto.getStatus()==0){//如果是草稿的话，以下步骤不再执行
            return ResponseResult.okResult("此操作是保存草稿操作");
        }

        //3.5 从文章内容中抽取图片,图片地址集合
        List<String> contentImageUrlList = chouquContentImage(wmnews);

        //4.关联文章内容中的图片与文章关系
            //说白了，就是操作wm_news_material表(新增)
        saveNewsMaterial(wmnews, contentImageUrlList, (short) 0);//0表示来源于内容

        //5.关联封面图片与文章的关系
            //获取封面图片
        fengmianImageToNews(dto, wmnews, contentImageUrlList);

        //异步调用自动审核逻辑业务
        //wmNewsAutoScanService.autoScanWmNews(wmnews.getId());
        //调用异步添加任务的延迟队列业务
        wmNewsTaskService.addNewsToTask(wmnews.getId(),wmnews.getPublishTime());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }



    /**
     * 封面图片文章的关系
     * @param dto
     * @param wmnews
     * @param contentImageUrlList
     */
    private void fengmianImageToNews(WmNewsDto dto, WmNews wmnews, List<String> contentImageUrlList) {
        List<String> fengmianImage = dto.getImages();
        if(dto.getType()==null){//自动
            //1.如果内容图片个数大于等于1小于3的话，我们认为是单图
            if(contentImageUrlList.size()>=1 && contentImageUrlList.size()<3){
                fengmianImage= contentImageUrlList.stream().limit(1).collect(Collectors.toList());
                wmnews.setType((short) 1);
            }else
            if(contentImageUrlList.size()>=3){
                fengmianImage= contentImageUrlList.stream().limit(3).collect(Collectors.toList());
                wmnews.setType((short) 3);
            }else{//封面中没有图片
                wmnews.setType((short) 0);
            }
            wmnews.setImages(StringUtils.join(fengmianImage,","));
            updateById(wmnews);
        }
        saveNewsMaterial(wmnews, fengmianImage, (short) 1);//表示来源于封面
    }

    /**
     * 抽取内容中的图片关联关系
     * @param wmnews
     * @param contentImageUrlList
     */
    private void saveNewsMaterial(WmNews wmnews, List<String> contentImageUrlList,Short type) {
        if (contentImageUrlList != null && contentImageUrlList.size() > 0) {
            //根据图片url集合，获取对应的素材对象集合
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, contentImageUrlList));
            //根据stream流去过滤解析素材id
            List<Integer> contentImageIds = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            //批量新增wm_news_material中间表
            wmNewsMaterialMapper.saveRelations(contentImageIds, wmnews.getId(), type);
        }
    }

    /**
     * 抽取的第二个方法，从内容中抽取图片
     */
    private List<String> chouquContentImage(WmNews wmNews) {
        List<String> imageList=new ArrayList<>();

        //1.获取文章内容
        String content = wmNews.getContent();
        //转换类型
        List<Map> contentList = JSONArray.parseArray(content, Map.class);
        for (Map map : contentList) {
            if(map.get("type").equals("image")){
                String path = (String) map.get("value");
                imageList.add(path);
            }
        }
        return imageList;

    }

    /**
     * 抽取的第一个方法，保存或者修改文章表wm_news表
     * @param wmnews
     */
    private void saveOrUpdateWnews(WmNews wmnews) {
        //判断是否是修改
        if(wmnews.getId()==null){//新增
            save(wmnews);
        }else{//修改
            //1.删除素材中间表
            LambdaQueryWrapper<WmNewsMaterial> queryWrapper=Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId,wmnews.getId());
            wmNewsMaterialMapper.delete(queryWrapper);
            //2.修改wm_news表
            updateById(wmnews);
        }
    }

    /**
     * 文章上下架操作
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.参数校验
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.根据文章id查询文章是否存在
        WmNews wmNews = getById(dto.getId());

        //3.如果不存在，则直接报异常
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //4.如果存在，判断当前文章状态是否为已发布
        if(wmNews.getStatus()!=WmNews.Status.PUBLISHED.getCode()){
            //5.如果不是已发布，则报异常
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_PUBLISH_STATUS);
        }

        //6.如果是已发布，则修改文章上下架状态
        wmNews.setEnable(dto.getEnable());
        updateById(wmNews);

        //7.发送消息给kafka
        Map map=new HashMap();
        map.put("articleId",wmNews.getArticleId());
        map.put("enable",dto.getEnable());
        kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));

        return ResponseResult.okResult("文章上下架成功");
    }
}
